package com.example.maoyanmovie.ui.fragment;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.maoyanmovie.base.BaseFragment;
import com.example.maoyanmovie.databinding.FragmentComingBinding;
import com.example.maoyanmovie.ui.adapter.MovieAdapter;
import com.example.maoyanmovie.utils.ToastUtils;
import com.example.maoyanmovie.viewmodel.ComingViewModel;

public class ComingFragment extends BaseFragment<FragmentComingBinding, ComingViewModel> {

    private MovieAdapter adapter;

    @Override
    protected FragmentComingBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentComingBinding.inflate(inflater, container, false);
    }

    @Override
    protected Class<ComingViewModel> getViewModelClass() {
        return ComingViewModel.class;
    }

    @Override
    protected void initView() {
        adapter = new MovieAdapter(getContext());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setAdapter(adapter);

        binding.swipeRefresh.setOnRefreshListener(() -> viewModel.loadComingMovies());
    }

    @Override
    protected void initData() {
        viewModel.loadComingMovies();
    }

    @Override
    protected void initObservers() {
        viewModel.movieListLiveData.observe(getViewLifecycleOwner(), movies -> {
            if (movies != null && !movies.isEmpty()) {
                adapter.setMovieList(movies);
            }
        });

        viewModel.errorLiveData.observe(getViewLifecycleOwner(), error -> {
            if (error != null) {
                ToastUtils.showShort(getContext(), "加载失败：" + error);
            }
        });

        viewModel.loadingLiveData.observe(getViewLifecycleOwner(), loading -> {
            binding.swipeRefresh.setRefreshing(loading != null && loading);
        });
    }
}
